/**
 * Markdown相关工具函数
 */

export interface TocItem {
  key: string;
  href: string;
  title: string;
  level: number;
  children?: TocItem[];
  expanded?: boolean;
}

/**
 * 从Markdown内容中提取目录结构
 * @param content Markdown内容
 * @returns 目录树
 */
export const extractToc = (content: string): TocItem[] => {
  const lines = content.split('\n');
  const flatToc: TocItem[] = [];
  let inCodeBlock = false;
  let inYamlBlock = false;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmedLine = line.trim();

    // 检查代码块开始/结束
    if (trimmedLine.startsWith('```')) {
      inCodeBlock = !inCodeBlock;
      continue;
    }

    // 检查YAML前置元数据块
    if (trimmedLine === '---') {
      if (i === 0 || inYamlBlock) {
        inYamlBlock = !inYamlBlock;
      } else if (!inYamlBlock) {
        const precedingLines = lines.slice(0, i);
        const hasOnlyValidPrecedingContent = precedingLines.every(l => {
          const trimmed = l.trim();
          return trimmed === '' || trimmed.startsWith('#') || trimmed.startsWith('//');
        });
        if (hasOnlyValidPrecedingContent) {
          inYamlBlock = true;
        }
      }
      continue;
    }

    // 跳过代码块和YAML块中的内容
    if (inCodeBlock || inYamlBlock) {
      continue;
    }

    // 匹配标题
    const headingMatch = trimmedLine.match(/^(#{1,6})\s+(.+)$/);
    if (headingMatch) {
      const title = headingMatch[2].trim();

      // 过滤掉可能的YAML属性、链接、代码等
      if (title.length > 0 &&
        !title.includes(':') &&
        !title.startsWith('http') &&
        !title.startsWith('`') &&
        !title.match(/^\[.*\]\(.*\)$/)) {

        const level = headingMatch[1].length;
        const key = `heading-${flatToc.length}`;
        const href = `#${key}`;

        flatToc.push({
          key,
          href,
          title,
          level,
          children: [],
          expanded: level <= 2 // 默认展开一二级标题
        });
      }
    }
  }

  return buildTocTree(flatToc);
};

/**
 * 构建树形目录结构
 * @param items 扁平的目录项列表
 * @returns 树形结构的目录
 */
const buildTocTree = (items: TocItem[]): TocItem[] => {
  const result: TocItem[] = [];
  const stack: TocItem[] = [];

  for (const item of items) {
    // 找到合适的父级
    while (stack.length > 0 && stack[stack.length - 1].level >= item.level) {
      stack.pop();
    }

    if (stack.length === 0) {
      // 顶级项目
      result.push(item);
    } else {
      // 添加到父级的children中
      const parent = stack[stack.length - 1];
      if (!parent.children) parent.children = [];
      parent.children.push(item);
    }

    stack.push(item);
  }

  return result;
};

/**
 * 更新目录项的展开状态
 * @param items 目录项列表
 * @param targetKey 目标key
 * @returns 更新后的目录项列表
 */
export const toggleTocExpanded = (items: TocItem[], targetKey: string): TocItem[] => {
  return items.map(item => {
    if (item.key === targetKey) {
      return { ...item, expanded: !item.expanded };
    }
    if (item.children) {
      return { ...item, children: toggleTocExpanded(item.children, targetKey) };
    }
    return item;
  });
};

/**
 * 平滑滚动到指定元素
 * @param elementId 元素ID
 * @param offset 偏移量（默认100px，避免被固定头部遮挡）
 */
export const scrollToElement = (elementId: string, offset: number = 100): void => {
  const element = document.getElementById(elementId);
  if (element) {
    const offsetTop = element.offsetTop - offset;
    window.scrollTo({ top: offsetTop, behavior: 'smooth' });
  }
};















